<template>
  <el-drawer
    title="新增配置"
    :visible.sync="$props.drawer"
    :before-close="handleClose"
    size="50%"
  >
    <el-form ref="form" :model="form" label-width="120px">
      <el-card v-for="(item, index) in form.items" :key="index" class="box-card" shadow="never">
        <div slot="header" class="clearfix">
          <div>节点配置{{ index + 1 }}</div>
          <!-- <div>
            <el-button v-if="form.items.length !== 0" size="mini" type="danger">删除</el-button>
          </div> -->
        </div>
        <div>
          <el-form-item label="审批节点名称" :prop="'items.' + index + '.approvalNode'" :rules="{ required: true, message: '审批节点名称不能为空'}">
            <div style="width: 60%;">
              <el-input v-model="item.approvalNode" placeholder="请输入审批节点名称" clearable size="small" />
            </div>
          </el-form-item>
          <el-form-item label="审批角色" :prop="'items.' + index + '.approvalRoleId'" :rules="{ required: true, message: '请选择审批角色'}">
            <div style="width: 60%;">
              <el-select v-model="item.approvalRoleId" filterable placeholder="请选择审批角色" clearable size="small" style="width: 100%">
                <el-option
                  v-for="sitem in $props.roleList"
                  :key="sitem.value"
                  :label="sitem.label"
                  :value="sitem.value"
                />
              </el-select>
            </div>
          </el-form-item>
        </div>
        <div class="operate-btn">
          <el-button v-if="form.items.length !== 1" size="mini" type="text" @click="delItem(index)">删除</el-button>
          <el-button v-if="(form.items.length - 1) === index" size="mini" type="text" @click="addItem">新增</el-button>
        </div>
      </el-card>
      <el-form-item>
        <div class="footer-btn">
          <el-button type="primary" :loading="loading" @click="onSubmit">{{ form.id ? '立即修改' : '立即创建' }}</el-button>
          <el-button @click="handleClose">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script>
import request from '@/utils/request'

export default {
  name: 'Form',
  props: {
    drawer: {
      type: Boolean,
      default: false
    },
    defaultValue: {
      type: Object,
      default: () => ({})
    },
    configList: {
      type: Array,
      default: () => []
    },
    roleList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: {
        items: []
      },
      loading: false
    }
  },
  watch: {
    configList(val) {
      const l = val.map(item => {
        return {
          'approvalNode': item.approvalNode,
          'approvalRoleId': `${item.approvalRoleId}`,
          'approvalLevel': item.approvalLevel
        }
      })
      this.form = {
        items: l
      }
    }
  },
  methods: {
    onSubmit() {
      // console.log(this.form)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const { items } = this.form
          const { roleList } = this.$props
          const params = items.map(item => {
            return {
              ...item,
              approvalRole: roleList.find(it => it.value === item.approvalRoleId).label
            }
          })
          if (params.length === 1) {
            params[0].approvalLevel = '1'
          } else {
            params[params.length - 1].approvalLevel = Number(params[params.length - 2].approvalLevel) + 1 + ''
          }
          const obj = {}
          params.forEach(item => {
            obj[item.approvalNode] = (obj[item.approvalNode] || 0) + 1
          })

          const names = []
          Object.entries(obj).forEach(([key, value]) => {
            if (value > 1) {
              names.push(key)
            }
          })

          if (names.length > 0) {
            this.$message({
              message: `节点名字：${names.join(',')} 重复`,
              type: 'error'
            })
            return
          }
          this.request(params)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    async request(params) {
      try {
        this.loading = true
        request({ url: 'system/approveConfig', method: 'post', data: params }).then(res => {
          if (res.code === 200) {
            this.visible = false
            this.$message({
              message: '保存成功',
              type: 'success',
              onClose: () => {
                this.$emit('add-success')
                this.$refs['form'].resetFields()
              }

            })
          }
        })
      } catch (error) {
        this.$message({
          message: error,
          type: 'warning'
        })
      } finally {
        this.loading = false
      }
    },
    addItem() {
      this.form.items.push({
        'approvalNode': '',
        'approvalRoleId': '',
        'approvalLevel': ''
      })
    },
    delItem(index) {
      this.form.items.splice(index, 1)
    },
    handleClose() {
      this.$emit('close:drawer', false)
    }
  }
}
</script>

<style scoped>
  .item {
    display: flex;
    justify-content: right;
  }
  .required {
    color: red;
  }
  .box-card {
    width: 80%;
    margin-left: 10%;
    margin-bottom: 10px;
  }
  .footer-btn {
    padding-top: 40px;
  }
  .clearfix {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .operate-btn {
    display: flex;
    justify-content: center;
    width: 100%;
    align-items: center;
  }
</style>
